// routes/wechatRoutes.js
const express = require('express');
const router = express.Router();
const { handleWechatMessage, verifySignature } = require('../modules/wechat');
const xml2js = require('xml2js');

/**
 * 解析微信XML消息为JS对象
 * @param {string} xml - 微信XML消息
 * @returns {Promise<Object>} - 解析后的消息对象
 */
const parseXML = (xml) => {
  return new Promise((resolve, reject) => {
    xml2js.parseString(xml, { trim: true, explicitArray: false }, (err, result) => {
      if (err) {
        reject(err);
      } else {
        resolve(result.xml);
      }
    });
  });
};

/**
 * 将JS对象转换为微信XML回复
 * @param {Object} obj - 回复消息对象
 * @returns {string} - XML格式的回复消息
 */
const buildXML = (obj) => {
  const builder = new xml2js.Builder({
    rootName: 'xml',
    cdata: true,
    headless: true
  });
  return builder.buildObject(obj);
};

// 微信服务器认证接口
router.get('/', (req, res) => {
  const { signature, timestamp, nonce, echostr } = req.query;
  console.log('req.query', req.query)
  // 验证签名
  if (verifySignature({ signature, timestamp, nonce })) {
    console.log('微信验证成功')
    // 验证成功，返回echostr
    res.send(echostr);
  } else {
    // 验证失败
    res.status(401).send('验证失败');
  }
});

// 接收微信消息并回复
router.post('/', express.text({ type: 'text/xml' }), async (req, res) => {
  try {
    // 解析微信发来的XML消息
    const message = await parseXML(req.body);
    console.log('微信接受message: ', message)
    // 处理消息并获取回复
    const reply = await handleWechatMessage(message);
    console.log('微信处理reply: ', reply)
    // 如果处理出错，返回默认回复
    if (reply.error) {
      const defaultReply = {
        ToUserName: message.FromUserName,
        FromUserName: message.ToUserName,
        CreateTime: Math.floor(Date.now() / 1000),
        MsgType: 'text',
        Content: '系统繁忙，请稍后再试~'
      };
      res.type('application/xml').send(buildXML(defaultReply));
      return;
    }
    
    // 将回复转换为XML并发送
    res.type('application/xml').send(buildXML(reply));
  } catch (error) {
    console.error('处理微信消息请求出错:', error);
    res.status(500).send('服务器内部错误');
  }
});

module.exports = router;